package com.itcam.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.mapper.MapperScannerConfigurer;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;

/**
 * Author:Cammy.Wu
 * Date:2024-05-06
 * Description:持久层配置类：连接池、sqlSessionFactory、Mapper代理对象
 *
 * 方式1：保留外部配置文件
 *
 * TODO：如果将dataSource和mybatis的组件配置到一起，出现@Value不生效的问题
 *      原因：mybatis的组件优先加载，@Value还没读取
 *      解决：分开配置
 */

@Configuration
public class MapperJavaConfig {

    // sqlSessionFactory加入ioc容器
    // mybatis -> sqlSessionFactoryBean[ioc] -> getObject() -> sqlSessionFactory
    // 方式一：外部指定mybatis配置文件
    @Bean
    public SqlSessionFactoryBean sqlSessionFactory(DataSource dataSource){
        SqlSessionFactoryBean sessionFactoryBean = new SqlSessionFactoryBean();

        // 指定配置文件等信息
        // 指定数据库连接池对象
        sessionFactoryBean.setDataSource(dataSource);

        // 指定外部的mybatis配置文件
        ClassPathResource resource = new ClassPathResource("mybatis-config.xml");
        sessionFactoryBean.setConfigLocation(resource);

        return  sessionFactoryBean;

    }

    // mapper代理对象加入到ioc
    @Bean
    public MapperScannerConfigurer mapperScannerConfigurer(){
        // Mapper代理对象的factoryBean -> 指定一个包 -> sqlSessionFactory -> sqlSession -> getMapper -> mapper代理对象 -> ioc
        MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
        mapperScannerConfigurer.setBasePackage("com.itcam.mapper");
        return mapperScannerConfigurer;
    }



}
